<template>
  <div class="dashboard-container">
    <div class="dashboard-left-panel">
      <div class="card device-status-card">
        <h3>当前装置情况</h3>
        <el-table
          :data="deviceStatusList"
          stripe
          style="width: 100%; flex: 1; overflow: auto"
          height="100%"
          class="device-table"
        >
          <el-table-column prop="name" label="装置名称" min-width="120"></el-table-column>
          <el-table-column
            prop="warningCount"
            label="预警数量"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="alarmCount"
            label="报警数量"
            width="100"
            align="center"
          ></el-table-column>
          <template #empty>
            <p class="no-data-text-small">暂无装置数据</p>
          </template>
        </el-table>
      </div>
      <div class="card risk-assessment-card">
        <h3>风险评估</h3>
        <el-table
          :data="riskAssessmentList"
          stripe
          style="width: 100%; flex: 1; overflow: auto"
          height="100%"
        >
          <el-table-column prop="deviceName" label="装置名称" min-width="120"></el-table-column>
          <el-table-column prop="riskLevel" label="风险等级" align="center">
            <template #default="{ row }">
              <span :class="getRiskLevelClass(row.riskLevel)">{{ row.riskLevel }}</span>
            </template>
          </el-table-column>
          <template #empty>
            <p class="no-data-text-small">暂无风险评估数据</p>
          </template>
        </el-table>
      </div>
    </div>

    <div class="dashboard-middle-panel">
      <div class="card key-metrics-card">
        <h3>关键指标概览</h3>
        <div class="metrics-grid">
          <div class="metric-item">
            <span class="metric-label">运行装置数量</span>
            <span class="metric-value"
              >{{ dashboardMetrics.runningDevices }} / {{ dashboardMetrics.totalDevices }} 台</span
            >
            <span class="metric-percentage">({{ runningPercentage }}%)</span>
          </div>
          <div class="metric-item">
            <span class="metric-label">总预警数量</span>
            <span class="metric-value">{{ dashboardMetrics.totalWarnings }} 个</span>
          </div>
          <div class="metric-item">
            <span class="metric-label">报警未处理</span>
            <span class="metric-value">{{ dashboardMetrics.undisposedAlarms }} 个</span>
            <span class="metric-percentage">({{ undisposedPercentage }}%)</span>
          </div>
          <div class="metric-item">
            <span class="metric-label">报警已处理</span>
            <span class="metric-value">{{ dashboardMetrics.disposedAlarms }} 个</span>
            <span class="metric-percentage">({{ disposedPercentage }}%)</span>
          </div>
        </div>
      </div>
      <div class="card device-carousel-card">
        <h3>装置概览</h3>
        <el-carousel :interval="4000" type="card" height="400px" indicator-position="none">
          <el-carousel-item v-for="device in carouselDevices" :key="device.id">
            <div class="carousel-item-content" @click="goToAnomalyDetectionMain(device.name)">
              <img :src="`${device.image}`" :alt="device.name" class="carousel-device-image" />
              <span class="carousel-device-name">{{ device.name }}</span>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>
    </div>

    <div class="dashboard-right-panel">
      <div class="card alarm-list-card">
        <h3>最新报警列表</h3>
        <el-table
          :data="dashboardAlarmList"
          stripe
          style="width: 100%"
          height="100%"
          class="alarm-table-display"
        >
          <el-table-column prop="sensorId" label="传感器" width="100"></el-table-column>
          <el-table-column prop="time" label="时间" width="100">
            <template #default="{ row }">
              {{ new Date(row.time).toLocaleTimeString('zh-CN', { hour12: false }) }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型"></el-table-column>
          <el-table-column prop="statusText" label="状态" width="100">
            <template #default="{ row }">
              <span
                :class="{
                  'status-undisposed-text': !row.disposed,
                  'status-disposed-text': row.disposed,
                }"
              >
                {{ row.status }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button
                link
                type="primary"
                :disabled="row.disposed"
                @click="handleAnalyzeAlarm(row)"
              >
                溯源
              </el-button>
              <el-button
                link
                :type="row.disposed ? 'success' : 'warning'"
                :disabled="row.disposed"
                @click="handleDisposeAlarm(row)"
              >
                {{ row.disposed ? '已处置' : '处置' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="info" size="small" @click="goToFaultInfoPage" style="margin-top: 15px"
          >查看全部报警</el-button
        >
      </div>
      <div class="card alarm-type-pie-card">
        <h3>报警类型占比</h3>
        <div class="chart-container">
          <canvas id="alarmTypePieChart"></canvas>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import {
  ElCarousel,
  ElCarouselItem,
  ElTable,
  ElTableColumn,
  ElButton,
  ElMessage,
} from 'element-plus'
import Chart from 'chart.js/auto' // For the pie chart

const router = useRouter()

// --------------------------------------------------------------------------------
// 响应式数据
// --------------------------------------------------------------------------------

const deviceStatusList = ref([]) // 从 /api/dashboard/device-status 获取
const dashboardMetrics = ref({
  // 从 /api/dashboard/key-metrics 获取
  runningDevices: 0,
  totalDevices: 0,
  totalWarnings: 0,
  undisposedAlarms: 0,
  disposedAlarms: 0,
  totalAlarms: 0,
})
const carouselDevices = ref([]) // 从 /api/devices 获取
const dashboardAlarmList = ref([]) // 从 /api/dashboard/latest-alarms 获取
const alarmTypeDistribution = ref({}) // 从 /api/dashboard/alarm-type-distribution 获取
const riskAssessmentList = ref([])

// --------------------------------------------------------------------------------
// 计算属性 (保持不变)
// --------------------------------------------------------------------------------

const runningPercentage = computed(() =>
  dashboardMetrics.value.totalDevices === 0
    ? 0
    : ((dashboardMetrics.value.runningDevices / dashboardMetrics.value.totalDevices) * 100).toFixed(
        1,
      ),
)
const undisposedPercentage = computed(() =>
  dashboardMetrics.value.totalAlarms === 0
    ? 0
    : (
        (dashboardMetrics.value.undisposedAlarms / dashboardMetrics.value.totalAlarms) *
        100
      ).toFixed(1),
)
const disposedPercentage = computed(() =>
  dashboardMetrics.value.totalAlarms === 0
    ? 0
    : ((dashboardMetrics.value.disposedAlarms / dashboardMetrics.value.totalAlarms) * 100).toFixed(
        1,
      ),
)

// --------------------------------------------------------------------------------
// 方法
// --------------------------------------------------------------------------------

let pieChartInstance = null // 用于存储饼图实例
let dashboardSimulateInterval = null // <-- 修正：在顶层声明，确保 onUnmounted 可以访问

const drawPieChart = () => {
  const ctx = document.getElementById('alarmTypePieChart').getContext('2d')
  if (!ctx) {
    console.error('DashboardView: Cannot get 2D context for pie chart canvas.')
    return
  }

  if (pieChartInstance) {
    pieChartInstance.destroy()
  }

  const labels = Object.keys(alarmTypeDistribution.value)
  const data = Object.values(alarmTypeDistribution.value)
  const backgroundColors = [
    '#FF6384',
    '#36A2EB',
    '#FFCE56',
    '#4BC0C0',
    '#9966FF',
    '#FF9933',
    '#C9CBCE',
    '#7B68EE',
  ]

  pieChartInstance = new Chart(ctx, {
    type: 'pie',
    data: {
      labels: labels,
      datasets: [
        {
          data: data,
          backgroundColor: backgroundColors.slice(0, labels.length),
          hoverOffset: 4,
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'right',
        },
        title: {
          display: false,
          text: '报警类型占比',
        },
      },
    },
  })
}

/**
 * 轮播图点击跳转到 AnomalyDetectionMain 页面，并传递装置名称。
 * @param {string} deviceName - 装置的名称。
 */
const goToAnomalyDetectionMain = (deviceName) => {
  console.log(`Navigating to AnomalyDetectionMain for device: ${deviceName}`)
  // 跳转到 AnomalyDetectionMain，并通过 query 参数传递装置名称
  router.push({ name: 'AnomalyDetection', query: { deviceName: deviceName } }).catch((err) => {
    // 捕获可能由 ElCarousel 销毁引起的路由错误
    if (err.name !== 'NavigationDuplicated' && err.name !== 'NavigationFailureType') {
      // Check for specific navigation errors
      console.error('Error navigating:', err)
      // Fallback to reload if navigation fails completely
      // location.reload();
    }
  })
}

const goToFaultInfoPage = () => {
  console.log('Navigating to fault info page.')
  router.push({ name: 'FaultInfo' })
}

/**
 * 仪表盘报警列表的“分析”按钮点击事件。
 * @param {Object} alarm - 报警对象。
 */
const handleAnalyzeAlarm = (alarm) => {
  console.log(`Dashboard: Analyzing alarm ${alarm.alarmId || alarm.sensorId}.`)
  // 跳转到故障溯源页面，并传递报警ID和传感器ID
  router.push({
    name: 'FaultTracing',
    params: { alarmId: alarm.alarmId || 'N/A', sensorId: alarm.sensorId, type: 'analysis' },
  })
}

/**
 * 仪表盘报警列表的“处置”按钮点击事件。
 * @param {Object} alarm - 报警对象。
 */
const handleDisposeAlarm = async (alarm) => {
  if (alarm && !alarm.disposed) {
    console.log(`Dashboard: Disposing alarm ${alarm.alarmId || alarm.sensorId}.`)

    // 模拟后端处置接口调用 (实际项目中需要调用后端)
    try {
      const response = await fetch(`/api/alarms/${alarm.alarmId}/dispose`, { method: 'POST' })
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
      const result = await response.json()
      if (!result.success) throw new Error(result.message || 'Backend dispose failed')

      // 更新前端状态
      const index = dashboardAlarmList.value.findIndex((a) => a.alarmId === alarm.alarmId)
      if (index !== -1) {
        dashboardAlarmList.value[index].disposed = true
        dashboardAlarmList.value[index].statusText = '报警已处置'
      }
      ElMessage.success(`报警 ${alarm.sensorId} 已处置！`)
    } catch (error) {
      console.error('Failed to dispose alarm:', error)
      ElMessage.error(`处置报警 ${alarm.sensorId} 失败！`)
    }
  } else if (alarm.disposed) {
    ElMessage.info(`报警 ${alarm.sensorId} 已处置，无需重复操作。`)
  }
}

/**
 * 根据风险等级返回对应的 CSS 类。
 * @param {string} level - 风险等级 (低, 中, 高)。
 */
const getRiskLevelClass = (level) => {
  if (level === '高') return 'risk-high'
  if (level === '中') return 'risk-medium'
  if (level === '低') return 'risk-low'
  return ''
}

// --------------------------------------------------------------------------------
// 数据获取方法 (对应接口文档)
// --------------------------------------------------------------------------------

const fetchDashboardData = async () => {
  try {
    // 1. 获取所有装置列表
    const devicesResponse = await fetch('/api/devices')
    const devicesData = await devicesResponse.json()
    carouselDevices.value = devicesData.map((d) => ({
      // 映射为轮播图所需格式
      id: d.id,
      name: d.name,
      image: `/img/${d.imageName}`, // 使用后端返回的 imageName
    }))
    console.log('-------------------------carouselDevices', carouselDevices)
    // 2. 获取装置实时状态概览
    const deviceStatusResponse = await fetch('/api/dashboard/device-status')
    const deviceStatusData = await deviceStatusResponse.json()
    deviceStatusList.value = deviceStatusData

    // 3. 获取关键指标概览
    const keyMetricsResponse = await fetch('/api/dashboard/key-metrics')
    const keyMetricsData = await keyMetricsResponse.json()
    dashboardMetrics.value = keyMetricsData

    // 4. 获取最新报警列表
    const latestAlarmsResponse = await fetch('/api/dashboard/latest-alarms')
    const latestAlarmsData = await latestAlarmsResponse.json()
    dashboardAlarmList.value = latestAlarmsData

    // 5. 获取报警类型占比
    const alarmTypeDistributionResponse = await fetch('/api/dashboard/alarm-type-distribution')
    const alarmTypeDistributionData = await alarmTypeDistributionResponse.json()
    alarmTypeDistribution.value = alarmTypeDistributionData

    // 新增：获取风险评估数据 (假设有 /api/dashboard/risk-assessment 接口)
    const riskAssessmentResponse = await fetch('/api/dashboard/risk-assessment')
    const riskAssessmentData = await riskAssessmentResponse.json()
    riskAssessmentList.value = riskAssessmentData // <-- 填充数据

    console.log('DashboardView: All dashboard data fetched successfully.')

    // 绘制饼图 (因为它依赖 alarmTypeDistribution)
    nextTick(() => {
      drawPieChart()
    })
  } catch (error) {
    console.error('DashboardView: Error fetching dashboard data, using mock data:', error)
    // Fallback to initial hardcoded mock data if any fetch fails
    // (This part uses the initial hardcoded data from the template's script setup)
    deviceStatusList.value = [
      { id: 'dev_union_alcohol', name: '联醇装置', warningCount: 5, alarmCount: 2, status: '运行' },
      {
        id: 'dev_desorption_system',
        name: '解吸浓缩系统装置',
        warningCount: 3,
        alarmCount: 1,
        status: '运行',
      },
      { id: 'dev_unit_c', name: '分离单元', warningCount: 0, alarmCount: 0, status: '待机' },
      { id: 'dev_unit_d', name: '精馏塔', warningCount: 1, alarmCount: 0, status: '运行' },
      { id: 'dev_unit_e', name: '反应器', warningCount: 0, alarmCount: 1, status: '故障' },
      { id: 'dev_unit_f', name: '泵站 A', warningCount: 2, alarmCount: 0, status: '运行' },
      { id: 'dev_unit_g', name: '压缩机', warningCount: 0, alarmCount: 0, status: '运行' },
    ]
    dashboardMetrics.value = {
      runningDevices: 5,
      totalDevices: 7,
      totalWarnings: 12,
      undisposedAlarms: 3,
      disposedAlarms: 7,
      totalAlarms: 10,
    }
    carouselDevices.value = [
      { id: 'dev_union_alcohol', name: '联醇装置', image: '/img/device.png' },
      { id: 'dev_desorption_system', name: '解吸浓缩系统装置', image: '/img/device1.png' },
      { id: 'dev_unit_c', name: '分离单元', image: '/img/device.png' },
      { id: 'dev_unit_d', name: '精馏塔', image: '/img/device1.png' },
      { id: 'dev_unit_e', name: '反应器', image: '/img/device.png' },
      { id: 'dev_unit_f', name: '泵站 A', image: '/img/device1.png' },
      { id: 'dev_unit_g', name: '压缩机', image: '/img/device.png' },
    ]
    dashboardAlarmList.value = [
      {
        alarmId: 'dal_1',
        sensorId: 'FIC1001',
        time: new Date(Date.now() - 1000 * 60 * 5).toISOString(),
        type: '高压',
        statusText: '报警未处置',
        disposed: false,
        deviceId: 'dev_union_alcohol',
      },
      {
        alarmId: 'dal_2',
        sensorId: 'FI615',
        time: new Date(Date.now() - 1000 * 60 * 10).toISOString(),
        type: '温度超限',
        statusText: '报警未处置',
        disposed: false,
        deviceId: 'dev_desorption_system',
      },
      {
        alarmId: 'dal_3',
        sensorId: 'PIC1003',
        time: new Date(Date.now() - 1000 * 60 * 15).toISOString(),
        type: '异常波动',
        statusText: '报警已处置',
        disposed: true,
        deviceId: 'dev_union_alcohol',
      },
      {
        alarmId: 'dal_4',
        sensorId: 'TE203',
        time: new Date(Date.now() - 1000 * 60 * 20).toISOString(),
        type: '通信故障',
        statusText: '报警未处置',
        disposed: false,
        deviceId: 'dev_desorption_system',
      },
      {
        alarmId: 'dal_5',
        sensorId: 'LI301',
        time: new Date(Date.now() - 1000 * 60 * 25).toISOString(),
        type: '读数错误',
        statusText: '报警已处置',
        disposed: true,
        deviceId: 'dev_desorption_system',
      },
    ]
    const fallbackDistribution = {}
    dashboardAlarmList.value.forEach((alarm) => {
      fallbackDistribution[alarm.type] = (fallbackDistribution[alarm.type] || 0) + 1
    })
    alarmTypeDistribution.value = fallbackDistribution
    riskAssessmentList.value = [
      { deviceName: '联醇装置', riskLevel: '中' },
      { deviceName: '解吸浓缩系统装置', riskLevel: '低' },
      { deviceName: '分离单元', riskLevel: '低' },
      { deviceName: '精馏塔', riskLevel: '低' },
      { deviceName: '反应器', riskLevel: '低' },
      { deviceName: '泵站 A', riskLevel: '低' },
      { deviceName: '压缩机', riskLevel: '低' },
    ]
    ElMessage.error('仪表盘数据加载失败，正在使用模拟数据！')
  }
}

// --------------------------------------------------------------------------------
// 生命周期钩子
// --------------------------------------------------------------------------------

onMounted(async () => {
  await fetchDashboardData() // 页面挂载时获取所有仪表盘数据

  // 启动模拟实时更新和饼图重绘 (如果后端没有实现实时推送)
  if (!dashboardSimulateInterval) {
    dashboardSimulateInterval = setInterval(async () => {
      console.log('DashboardView: Simulating real-time updates and refetching dashboard data.')
      await fetchDashboardData() // 重新获取所有数据，模拟实时更新
    }, 5000) // 每5秒重新获取一次
  }
})

onUnmounted(() => {
  if (pieChartInstance) {
    pieChartInstance.destroy()
  }
  if (dashboardSimulateInterval) {
    // <-- 修正：检查是否定义
    clearInterval(dashboardSimulateInterval)
  }
})
</script>

<style scoped>
/* 整个仪表盘容器 */
.dashboard-container {
  display: flex;
  height: 100vh;
  width: 100%;
  padding: 20px;
  gap: 20px;
  background-color: #f0f2f5;
  box-sizing: border-box;
  overflow: hidden; /* 防止内容溢出，内部滚动条由各卡片控制 */
}

/* 左、中、右面板的通用样式 */
.dashboard-left-panel,
.dashboard-middle-panel,
.dashboard-right-panel {
  display: flex;
  flex-direction: column;
  gap: 20px; /* 内部卡片之间的间距 */
  min-height: 0; /* 允许 flex 项目正确收缩 */
  box-sizing: border-box;
}

/* 各面板的宽度比例 */
.dashboard-left-panel {
  flex: 1.2;
  min-width: 280px;
}

.dashboard-middle-panel {
  flex: 2;
  min-width: 400px;
}

.dashboard-right-panel {
  flex: 1.5;
  min-width: 350px;
}

/* 通用卡片样式 */
.card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  display: flex;
  flex-direction: column;
  min-height: 0; /* 允许内容过多时滚动 */
  box-sizing: border-box;
}

.card h3 {
  color: #3f51b5;
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 1.2em;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  flex-shrink: 0;
}

.placeholder-text {
  color: #888;
  text-align: center;
  padding: 50px 0;
  font-size: 1.1em;
}

/* 左侧面板 - 装置情况表格 */
.device-status-card {
  flex: 1; /* 占据左侧面板一半高度 */
  overflow: hidden; /* 隐藏表格的滚动条 */
}
/* Element Plus table 自身将有滚动条 */
.device-table {
  flex: 1; /* 表格占据父卡片的剩余空间 */
  overflow: auto; /* Element Plus Table 内部会有滚动条 */
}
/* Ensure the table cell content is aligned correctly */
.el-table__cell {
  text-align: center !important; /* 强制所有单元格内容居中 */
}
.el-table__header-wrapper th {
  text-align: center !important; /* 强制表头居中 */
}

/* 左侧面板 - 风险评估 */
.risk-assessment-card {
  flex: 1; /* 占据左侧面板另一半高度 */
  /* background-color: #e8f5e9; */ /* 移除颜色 */
  /* border: 1px dashed #a5d6a7; */ /* 移除边框 */
}
/* 风险等级的颜色样式 */
.risk-low {
  color: #28a745; /* 绿色 */
  font-weight: bold;
}
.risk-medium {
  color: #ffc107; /* 橙色 */
  font-weight: bold;
}
.risk-high {
  color: #dc3545; /* 红色 */
  font-weight: bold;
}
/* 中间面板 - 关键指标概览 */
.key-metrics-card {
  flex-shrink: 0; /* 不收缩，保持内容所需高度 */
  height: auto; /* 高度由内容决定 */
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
}
.metric-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f0f4f8;
  padding: 15px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.metric-label {
  font-size: 0.9em;
  color: #666;
  margin-bottom: 5px;
}
.metric-value {
  font-size: 1.6em;
  font-weight: bold;
  color: #3f51b5;
}
.metric-percentage {
  font-size: 0.8em;
  color: #888;
  margin-top: 3px;
}

/* 中间面板 - 装置轮播图 */
.device-carousel-card {
  flex: 1; /* 占据中间面板剩余高度 */
}
.el-carousel {
  width: 100%;
}
.carousel-item-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f5f5;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.3s ease;
}
.carousel-item-content:hover {
  transform: scale(1.03);
}
.carousel-device-image {
  max-width: 80%;
  max-height: 70%;
  object-fit: contain;
  margin-bottom: 5px;
}
.carousel-device-name {
  font-size: 1.1em;
  font-weight: bold;
  color: #555;
}

/* 右侧面板 - 报警列表 */
.alarm-list-card {
  flex: 1.5; /* 占据右侧面板更多高度 */
  overflow: hidden; /* 隐藏表格的滚动条 */
}
.alarm-table-display {
  /* Element Plus table 自身将有滚动条 */
  flex: 1; /* 表格占据父卡片的剩余空间 */
  overflow: auto;
}
.status-undisposed-text {
  color: #ef6c00;
  font-weight: bold;
}
.status-disposed-text {
  color: #388e3c;
  font-weight: bold;
}

/* 右侧面板 - 报警类型占比饼图 */
.alarm-type-pie-card {
  flex: 1;
}
.alarm-type-pie-card .chart-container {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}
</style>
